package com.dhcc.bpm.modules.safe.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.enums.ConfigType;
import com.dhcc.bpm.common.redisMessage.RedisMessageSender;
import com.dhcc.bpm.modules.api.entity.Api;
import com.dhcc.bpm.modules.api.service.IApiService;
import com.dhcc.bpm.modules.orga.entity.App;
import com.dhcc.bpm.modules.orga.entity.ProduceApply;
import com.dhcc.bpm.modules.orga.entity.TestApply;
import com.dhcc.bpm.modules.orga.service.IAppService;
import com.dhcc.bpm.modules.orga.service.IProduceApplyService;
import com.dhcc.bpm.modules.orga.service.ITestApplyService;
import com.dhcc.bpm.modules.safe.entity.Flow;
import com.dhcc.bpm.modules.safe.service.IFlowService;
import com.dhcc.bpm.modules.safe.vo.FlowVO;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
/**
 * @ClassName FlowController
 * @Description 流量管理表 控制器
 * @Author daina
 * @Date 2020/2/21 14:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 */
@RestController
@AllArgsConstructor
@RequestMapping("bpm-safe/opcflow")
@io.swagger.annotations.Api(value = "流量管理表", tags = "流量管理表接口")
public class FlowController extends BladeController {
	private static final Logger log = LoggerFactory.getLogger(FlowController.class);

	private IFlowService flowService;
	private IApiService apiService;
	private IAppService appService;
	private ITestApplyService testApplyService;
	private IProduceApplyService produceApplyService;

	@Autowired
	private RedisMessageSender redisMessageSender;

	/**
	 * @Description 详情
	 * @Author daina
	 * @Date 21:33 2020/2/21
	 * @param flow
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.safe.entity.Flow>
	 **/
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入flow")
	@ApiLog("详情")
	@Log(title = "详情",businessType = BusinessType.SELECT)
	public R<Flow> detail(Flow flow) {
		Flow detail = flowService.getOne(Condition.getQueryWrapper(flow));
		return R.data(detail);
	}

	/**
	 * @Description 分页 流量管理表
	 * @Author daina
	 * @Date 21:33 2020/2/21
	 * @param flow
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.safe.entity.Flow>>
	 **/
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入flow")
	@ApiLog("分页")
	@Log(title = "分页",businessType = BusinessType.SELECT)
	public R<IPage<Flow>> list(Flow flow, Query query) {
		IPage<Flow> pages = flowService.page(Condition.getPage(query), Condition.getQueryWrapper(flow));
		return R.data(pages);
	}
	/**
	 * @Description 修改 控制状态
	 * @Author daina
	 * @Date 21:33 2020/2/21
	 * @param flow
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/changeStatus")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入flow")
	@ApiLog("修改启停状态")
	@Log(title = "修改启停状态", businessType = BusinessType.UPDATE)
	public R changeStatus(@Valid @RequestBody Flow flow) {
		// flag 限流类型 2：渠道接口限流
		String flag = "2";
		// 渠道接口限流 RefreshFlag 0：未刷新
		flow.setRefreshStatus("0");
		if(flag.equals(flow.getFlowType())){
			FlowVO flowVo = new FlowVO();
			flowVo.setOpcApiId(flow.getOpcApiId());
			flowVo.setOpcAppId(flow.getOpcAppId());
			flowVo.setEnv(flow.getEnv());
			flowVo.setFlowType(flow.getFlowType());
			Flow fl = flowService.selectAppFlowByAppApi(flowVo);
			if(fl == null){
				return R.fail(222, "该条数据异常！");
			}
			flow.setId(fl.getId());
		}
		return R.status(flowService.updateById(flow));

	}

	/**
	 * @Description 自定义分页 流量管理表
	 * @Author daina
	 * @Date 21:33 2020/2/21
	 * @param flow
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.safe.vo.FlowVO>>
	 **/
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入flow")
	@ApiLog("自定义分页")
	@Log(title = "自定义分页",businessType = BusinessType.SELECT)
	public R<IPage<FlowVO>> page(FlowVO flow, Query query) {
		IPage<FlowVO> pages = flowService.selectFlowPage(Condition.getPage(query), flow);
		return R.data(pages);
	}

	@GetMapping("/pageBybasePrdt")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入flow")
	@ApiLog("自定义分页")
	@Log(title = "自定义分页",businessType = BusinessType.SELECT)
	public R<IPage<FlowVO>> pageBybasePrdt(FlowVO flow, Query query) {
		IPage<FlowVO> pages = flowService.pageBybasePrdt(Condition.getPage(query), flow);
		return R.data(pages);
	}

	/**
	 * @Description 新增 流量管理表
	 * @Author daina
	 * @Date 21:34 2020/2/21
	 * @param flow
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入flow")
	@ApiLog("新增 流量管理表")
	@Log(title = "新增",businessType = BusinessType.UPDATE)
	public R save(@Valid @RequestBody Flow flow) {
		return R.status(flowService.save(flow));
	}

	/**
	 * @Description 修改 流量管理表
	 * @Author daina
	 * @Date 21:34 2020/2/21
	 * @param flow
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入flow")
	@ApiLog("修改 流量管理表")
	@Log(title = "修改 流量管理表",businessType = BusinessType.UPDATE)
	public R update(@Valid @RequestBody Flow flow) {
		return R.status(flowService.updateById(flow));
	}

	/**
	 * @Description 新增或修改 流量管理表
	 * @Author daina
	 * @Date 21:34 2020/2/21
	 * @param flow
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入flow")
	@ApiLog("新增或修改流量管理表")
	@Log(title = "新增或修改流量管理表",businessType = BusinessType.UPDATE)
	public R submit(@Valid @RequestBody FlowVO flow) {
		Integer s = 1;
		Integer m = 60;
		Integer h = 3600;
		Integer d = 86400;
		Integer d30 = 2592000;
		Integer order1 = 1;
		Integer order2 = 2;
		Integer order3 = 3;
		Integer order4 = 4;
		Integer order5 = 5;
		// 限流类型 1.应用限流；2.渠道接口限流；3 .接口限流
		String type = "3";
		String type1 = "1";
		try {
			boolean flag = false;
//			if(type.equals(flow.getFlowType()) || type1.equals(flow.getFlowType())){
				if (flow.getFlowControlCycle().equals(order1)) {
					flow.setFlowControlSeconds(s);
				} else if (flow.getFlowControlCycle().equals(order2)) {
					flow.setFlowControlSeconds(m);
				} else if (flow.getFlowControlCycle().equals(order3)) {
					flow.setFlowControlSeconds(h);
				} else if (flow.getFlowControlCycle().equals(order4)) {
					flow.setFlowControlSeconds(d);
				}else if (flow.getFlowControlCycle().equals(order5)) {
					flow.setFlowControlSeconds(d30);
				}
//			}
			// 0:未刷新
			flow.setRefreshStatus("0");
//			if(!type.equals(flow.getFlowType())){
//				flow.setGatewayCode("");
//			}
			if (null != flow.getId()) {
				flag = flowService.updateById(flow);
			} else {
				flag = flowService.saveOrUpdate(flow);
			}
			return R.status(flag);
		}catch (Exception e){
			log.error("更新异常：{}", e);
			return R.status(false);
		}
	}

	/**
	 * @Description 删除 流量管理表
	 * @Author daina
	 * @Date 21:34 2020/2/21
	 * @param ids
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@ApiLog("删除 流量管理表")
	@Log(title = "删除",businessType = BusinessType.DELETE)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(flowService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * @Description 刷新限流配置
	 * @Author daina
	 * @Date 21:35 2020/2/21
	 * @param env
	 * @param flowType
	 * @param productId
	 * @return org.springblade.core.tool.api.R
	 **/
	@PostMapping("/refresh")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "刷新限流配置", notes = "限流配置")
	@ApiLog("刷新限流配置")
	@Log(title = "刷新限流配置", businessType = BusinessType.REFRESH)
	public R refreshRoute(@ApiParam(value = "主键集合", required = true) @RequestParam String env,
						  @ApiParam(value = "主键集合", required = true) @RequestParam String flowType,
						  @ApiParam(value = "主键集合", required = true) @RequestParam String productId) {
		try {
			String message = redisMessageSender.format(ConfigType.RATELIMET.name(), "刷新限流配置信息");
			redisMessageSender.sendMessageToGateway("", message);
			FlowVO flow = new FlowVO();
			flow.setRefreshStatus("1");
			flow.setEnv(env);

			// 限流类型 1.应用限流；2.渠道接口限流；3 .接口限流
			String type = "3";
			if (type.equals(flowType)){
				flow.setFlowType(flowType);
				int result =flowService.updateRefreshStatus(flow);
				if(result>=0){
					return R.status(true);
				}
				return R.status(false);
			}else{
				int result2 =flowService.refreshStatus(flow);
				if(result2>=0){
					return R.status(true);
				}
				return R.status(false);
			}
		}catch (Exception e){
			log.error("刷新限流配置失败:{}", e);
			return R.status(false);
		}
	}

	/**
	 * @Description 应用流量详情
	 * @Author daina
	 * @Date 21:35 2020/2/21
	 * @param flowVo
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.safe.entity.Flow>
	 **/
	@GetMapping("/flowDetail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入flow")
	@ApiLog("应用流量详情")
	@Log(title = "应用流量详情",businessType = BusinessType.SELECT)
	public R<Flow> flowDetail(FlowVO flowVo) {
		FlowVO detail = new FlowVO();
		App app = appService.getById(flowVo.getOpcAppId());
		if(app != null){
			String appCode = "";
			// 环境类型 1： 生产
			String env = "1";
			if(env.equals(flowVo.getEnv())){
				appCode = app.getAppId();
			}else{
				appCode = app.getTestAppId();
			}
			Flow flow = flowService.selectAppFlowByAppId(appCode, flowVo.getEnv());
			if(null != flow){
				BeanUtils.copyProperties(flow, detail);
			}
			if(env.equals(flowVo.getEnv())){
				detail.setOpcAppId(app.getAppId());
			}else{
				detail.setOpcAppId(app.getTestAppId());
			}
			detail.setAppName(app.getAppName());
			detail.setOrgaName(app.getOrgaName());
			Long appId = Long.valueOf(flowVo.getOpcAppId());
			if(env.equals(flowVo.getEnv())){
				ProduceApply produceApply = new ProduceApply();
				produceApply.setAppId(appId);
				ProduceApply produceApplydetail = produceApplyService.getOne(Condition.getQueryWrapper(produceApply).isNull("pid"));
				if(produceApplydetail != null){
					detail = produceApplyGetDetail(detail,produceApplydetail);
				}
				if(produceApplydetail == null){
					detail.setApplyQps(0L);
					detail.setApprovalQps(0L);
				}
			}else{
				TestApply testApply = new TestApply();
				testApply.setAppId(appId);
				TestApply testApplyDetail = testApplyService.getOne(Condition.getQueryWrapper(testApply));
				if (testApplyDetail != null){
					detail = testApplyGetDetail(detail,testApplyDetail);
				}
				if(testApplyDetail == null){
					detail.setApplyQps(0L);
					detail.setApprovalQps(0L);
				}
			}
		}
		return R.data(detail);
	}

	/**
	 * @Description 接口流量详情
	 * @Author daina
	 * @Date 21:35 2020/2/21
	 * @param flowVo
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.safe.entity.Flow>
	 **/
	@GetMapping("/apiFlowDetail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入flow")
	@ApiLog("接口流量详情")
	@Log(title = "接口流量详情",businessType = BusinessType.SELECT)
	public R<Flow> apiFlowDetail(FlowVO flowVo) {
		FlowVO detail = new FlowVO();
		Api api = apiService.getById(flowVo.getOpcApiId());
		App app = appService.getById(flowVo.getOpcAppId());
		String opcAppId = flowVo.getOpcAppId();
		// 环境类型 1：生产
		String env = "1";
		if(env.equals(flowVo.getEnv())){
			flowVo.setOpcAppId(app.getAppId());
		}else{
			flowVo.setOpcAppId(app.getTestAppId());
		}
		Long appId = Long.valueOf(opcAppId);
		if(env.equals(flowVo.getEnv())){
			ProduceApply produceApply = new ProduceApply();
			produceApply.setAppId(appId);
			ProduceApply produceApplydetail = produceApplyService.getOne(Condition.getQueryWrapper(produceApply).isNull("pid"));
			if(produceApplydetail != null){
				detail.setAccessPolicy(produceApplydetail.getAccessPolicy());
				detail = produceApplyGetDetail(detail,produceApplydetail);
			}
			if(produceApplydetail == null){
				detail.setApplyQps(0L);
				detail.setApprovalQps(0L);
			}
		}else{
			TestApply testApply = new TestApply();
			testApply.setAppId(appId);
			TestApply testApplyDetail = testApplyService.getOne(Condition.getQueryWrapper(testApply));
			if (testApplyDetail != null){
				detail.setAccessPolicy(testApplyDetail.getAccessPolicy());
				detail = testApplyGetDetail(detail,testApplyDetail);
			}
			if(testApplyDetail == null){
				detail.setApplyQps(0L);
				detail.setApprovalQps(0L);
			}
		}
		if (null != api ) {
			Flow flow = flowService.selectAppFlowByAppApi(flowVo);
			if (flow != null) {
				BeanUtils.copyProperties(flow, detail);
			}
			detail.setOpcApiId(flowVo.getOpcApiId());
			detail.setApiCode(api.getApiCode());
			detail.setApiName(api.getApiName());
			if(env.equals(flowVo.getEnv())){
				detail.setOpcAppId(app.getAppId());
			}else{
				detail.setOpcAppId(app.getTestAppId());
			}
			detail.setAppName(app.getAppName());
			detail.setOrgaName(app.getOrgaName());
		}

		return R.data(detail);
	}
	/**
	 * @Author daina
	 * @Description 公共方法
	 * @Param detail
	 * @Param produceApplydetail
	 * @return com.dhcc.bpm.modules.safe.vo.FlowVO
	 **/
	public FlowVO produceApplyGetDetail(FlowVO detail,ProduceApply produceApplydetail){
		if (produceApplydetail.getApplyQps() != null){
			detail.setApplyQps(produceApplydetail.getApplyQps());
		}else {
			detail.setApplyQps(0L);
		}
		if (produceApplydetail.getApprovalQps() != null){
			detail.setApprovalQps(produceApplydetail.getApprovalQps());
		}else {
			detail.setApprovalQps(0L);
		}
		return detail;
	}
	/**
	 * @Author daina
	 * @Description 公共方法
	 * @Date 13:48 2020/2/21
	 * @Param [detail, testApplyDetail]
	 * @return com.dhcc.bpm.modules.safe.vo.FlowVO
	 **/
	public FlowVO testApplyGetDetail(FlowVO detail,TestApply testApplyDetail){
		if (testApplyDetail.getApplyQps() != null){
			detail.setApplyQps(testApplyDetail.getApplyQps());
		}else {
			detail.setApplyQps(0L);
		}
		if (testApplyDetail.getApprovalQps() != null){
			detail.setApprovalQps(testApplyDetail.getApprovalQps());
		}else {
			detail.setApprovalQps(0L);
		}
		return detail;
	}
	/**
	 * @Description 自定义分页 接口-渠道限流
	 * @Author wjh
	 * @Date 2021年3月9日09:50:17
	 * @param flow
	 * @param query
	 **/
	@GetMapping("/appPage")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入flow")
	@ApiLog("自定义分页")
	@Log(title = "自定义分页",businessType = BusinessType.SELECT)
	public R<IPage<FlowVO>> apppage(FlowVO flow, Query query) {
		flow.setFlowType("1");
		IPage<FlowVO> pages = flowService.selectFlowPageByApp(Condition.getPage(query), flow);
		return R.data(pages);
	}
}
